<template>
  <div class="factory-report-container">
    <el-card class="factory-report-card">
      <!-- 页面头部 -->
      <div class="report-header">
        <div class="header-left">
          <h1 class="page-title">出厂检验报告</h1>
          <p class="page-subtitle">创建和管理产品检验报告</p>
        </div>
        <div class="header-right">
                                <el-button 
                        type="info" 
                        @click="goToList" 
                        class="back-btn"
                      >
                        返回列表
                      </el-button>
          <el-button 
            type="warning" 
            @click="goToStandardMaintain" 
            class="standard-btn"
          >
            查看技术标准
          </el-button>
          <el-button 
            type="primary" 
            @click="goToNewReport" 
            class="new-report-btn"
          >
            新建报告
          </el-button>
        </div>
      </div>
      <!-- 基本信息表单 -->
      <div class="form-section">
        <div class="report-code-row" style="margin-bottom: 12px; font-size: 16px; color: #1677ff;">
          报告编号：{{ generateReportCode() }}
        </div>
        <div class="standard-version-row" style="margin-bottom: 12px; font-size: 15px; color: #888;">
          标准版本号：{{ displayStandardVersionId || '未设置' }}
        </div>

        <div class="section-header">
          <h3 class="section-title">基本信息</h3>
          <div class="section-divider"></div>
        </div>
        <el-form :model="formData" label-width="140px" class="base-form" :rules="formRules" ref="baseFormRef">
          <el-row :gutter="20" class="form-row">
            <el-col :xs="24" :sm="12" class="form-col">
            <el-form-item label="报告日期" prop="date" class="form-item">
              <el-date-picker 
                v-model="baseInfo.date" 
                type="date" 
                placeholder="请选择报告日期" 
                :disabled="!isEditing"
                class="form-input"
              />
            </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" class="form-col">
            <el-form-item label="客户名称" prop="customer" class="form-item">
                <div class="autocomplete-with-delete">
              <el-autocomplete 
                v-model="baseInfo.customer" 
                :fetch-suggestions="queryCustomerHistory"
                placeholder="请输入客户名称" 
                :disabled="!isEditing"
                class="form-input"
                @select="onCustomerSelect"
                @blur="saveCustomerHistory"
              />
                  <el-button 
                    v-if="isEditing && baseInfo.customer"
                    type="danger" 
                    size="small" 
                    @click="deleteCustomerHistory(baseInfo.customer)"
                    class="delete-history-btn"
                    title="删除此客户记录"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
          </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="form-row">
            <el-col :xs="24" :sm="12" class="form-col">
            <el-form-item label="车牌号" prop="plate" class="form-item">
                <div class="autocomplete-with-delete">
              <el-autocomplete 
                v-model="baseInfo.plate" 
                :fetch-suggestions="queryPlateHistory"
                placeholder="请输入车牌号" 
                :disabled="!isEditing"
                class="form-input"
                @select="onPlateSelect"
                @blur="savePlateHistory"
              />
                  <el-button 
                    v-if="isEditing && baseInfo.plate"
                    type="danger" 
                    size="small" 
                    @click="deletePlateHistory(baseInfo.plate)"
                    class="delete-history-btn"
                    title="删除此车牌记录"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
            </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" class="form-col">
            <el-form-item label="产品名称" prop="template" class="form-item">
              <el-select 
                v-model="selectedTemplate" 
                placeholder="请选择产品模板" 
                @change="onTemplateChange" 
                :disabled="!isEditing"
                class="form-input"
              >
                <el-option label="滦星牌箱板纸" value="coated" />
                <el-option label="滦月牌高强瓦楞原纸" value="corrugated" />
              </el-select>
            </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="form-row">
            <el-col :xs="24" :sm="12" class="form-col">
            <el-form-item v-if="selectedTemplate === 'corrugated'" label="产品等级" prop="corrugatedLevel" class="form-item">
              <el-select 
                v-model="corrugatedLevel" 
                placeholder="请选择产品等级" 
                @change="onCorrugatedLevelChange" 
                :disabled="!isEditing"
                class="form-input"
              >
                <el-option label="AAA级" value="AAA级" />
                <el-option label="A级" value="A级" />
              </el-select>
            </el-form-item>
            <el-form-item v-else label="产品等级" prop="level" class="form-item">
              <el-input 
                v-model="baseInfo.level" 
                placeholder="请输入产品等级" 
                :disabled="!isEditing"
                class="form-input"
              />
            </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 克重组管理 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">检测数据</h3>
          <div class="section-divider"></div>
        </div>
            <div class="weight-groups-container">
          <div v-for="(group, idx) in weightGroups" :key="group.id" class="weight-group-card">
            <el-card shadow="hover" class="group-card">
              <div class="group-header">
                <div class="group-title">
                  <el-form-item label="克重" class="weight-input-item" :rules="[{ required: true, message: '请输入克重', trigger: 'blur' }]">
                    <el-input 
                      v-model="group.weight" 
                      placeholder="请输入克重" 
                      @change="() => { 
                        updateGroupStandardByWeight(group);
                        group.items.forEach(item => judgeItem(item, group));
                      }" 
                      :disabled="!isEditing"
                      class="weight-input"
                    />
                    <span v-if="group.weight && weightGroups.filter(g => g.weight === group.weight).length > 1" class="weight-suffix" style="margin-right: 16px;">
                      {{ getDisplayWeight(group, idx) }}
                    </span>
                    <div class="input-tip" style="color:#888;font-size:12px;margin-top:2px;"><span style='color:#f56c6c;font-weight:bold;margin-right:4px;'>*</span>输入克重后按回车或点空白处自动填充标准</div>
                  </el-form-item>
                </div>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeWeightGroup(idx)" 
                  :disabled="!isEditing"
                  class="delete-btn"
                >
                  删除
                </el-button>
              </div>
              <div class="table-wrapper">
              <el-table :data="group.items" border class="data-table">
                <el-table-column prop="name" label="指标名称" width="160" />
                <el-table-column prop="unit" label="单位" width="100" />
                <el-table-column prop="standard" label="标准" width="140" />
                <el-table-column prop="value" label="实测数据" width="160">
                  <template #default="scope">
                    <el-input 
                      v-model="scope.row.value" 
                      size="small" 
                      placeholder="必填"
                      class="required-input"
                      :disabled="!isEditing"
                        @change="() => judgeItem(scope.row, group)"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="result" label="判定" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.result === '合格' ? 'success' : (scope.row.result === '不合格' ? 'danger' : 'info')">
                      {{ scope.row.result || '' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
              </div>
            </el-card>
          </div>
        </div>
        
        <!-- 添加克重组按钮 - 移动到列表底部，方便操作 -->
        <div class="add-weight-section">
          <el-button
            type="primary"
            @click="addWeightGroup"
            :disabled="weightGroups.length >= MAX_GROUPS || !isEditing"
            class="add-weight-btn"
          >
            添加克重组
          </el-button>
        </div>
      </div>
                         <!-- 结论和设置 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">结论和设置</h3>
          <div class="section-divider"></div>
        </div>
        
        <div class="conclusion-section">
          <div class="seal-setting">
            <el-switch
              v-model="useSeal"
              active-text="加盖电子印章"
              inactive-text="不加盖印章"
              :disabled="!isEditing"
              class="seal-switch"
            />
            <span class="seal-desc">选择是否在结论上加盖电子印章</span>
          </div>
          
          <div class="conclusion-display">
            <span class="conclusion-label">结论：</span>
            <el-tag 
              :type="conclusion === '批次合格' ? 'success' : (conclusion === '不合格' ? 'danger' : 'info')"
              class="conclusion-tag"
            >
              {{ conclusion }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-section">
        <div class="action-buttons">
          <div class="primary-actions">
            <el-tooltip 
              :content="!isSaved ? '请先保存报告' : isEditing ? '请先完成编辑' : ''" 
              placement="top" 
              :disabled="isSaved && !isEditing"
            >
              <el-button type="info" @click="showPreview" :disabled="!isSaved || isEditing" class="action-btn">
                预览报告
              </el-button>
            </el-tooltip>
            <el-tooltip 
              :content="!isSaved ? '请先保存报告' : isEditing ? '请先完成编辑' : ''" 
              placement="top" 
              :disabled="isSaved && !isEditing"
            >
              <el-button type="primary" @click="generatePDF" :disabled="!isSaved || isEditing" class="action-btn">
              导出PDF
            </el-button>
            </el-tooltip>
          </div>
          
          <div class="secondary-actions">
            <el-button type="success" @click="saveReport" :disabled="isSaved" class="action-btn">
              保存
            </el-button>
            <el-button v-if="isSaved" type="warning" @click="onEdit" :disabled="!isSaved" class="action-btn">
              {{ isEditing ? '完成编辑' : '编辑' }}
            </el-button>
            <el-button type="info" @click="openSignatureManage" class="action-btn">
              签名管理
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>

  <!-- 预览对话框 -->
  <el-dialog
    v-model="previewVisible"
    title="报告预览"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="preview-dialog"
  >
    <div class="preview-container">
      <div ref="previewRef" class="pdf-report-template preview-template">
        <div style="width:100%;height:100%;">
          <!-- 公司名、标题、LOGO -->
          <div style="display:flex;align-items:center;justify-content:space-between;">
            <div style="width:90px;height:60px;display:flex;align-items:center;justify-content:center;">
              <img src="/logo.png" style="max-width:100%;max-height:100%;object-fit:contain;" />
            </div>
            <div style="flex:1;text-align:center;margin:0 16px;">
              <div style="font-size:22px;font-weight:bold;">唐山市冀滦纸业有限公司</div>
              <div style="font-size:18px;margin-top:2px;">出厂检验报告</div>
            </div>
            <div style="width:90px;height:60px;"></div>
          </div>
          <!-- 报告日期和报告编号行 -->
          <div style="display:flex;justify-content:space-between;align-items:center;font-size:14px;margin:8px 0 0 0;">
            <span>报告编号：{{ generateReportCode() }}</span>
            <span>报告日期：{{ baseInfo.date }}</span>
          </div>
          <!-- 信息区表格（客户名称、车牌号、产品名称、产品等级） -->
          <table style="width:100%;border-collapse:collapse;font-size:14px;margin-top:8px;">
            <tr>
              <td class="pdf-td" style="width:39px;">客户名称</td>
              <td class="pdf-td" style="width:83px;">{{ baseInfo.customer }}</td>
              <td class="pdf-td" style="width:100px;">车牌号</td>
              <td class="pdf-td" style="width:100px;">{{ baseInfo.plate }}</td>
            </tr>
            <tr>
              <td class="pdf-td" style="width:39px;">产品名称</td>
              <td class="pdf-td" style="width:83px;">{{ baseInfo.product }}</td>
              <td class="pdf-td" style="width:100px;">产品等级</td>
              <td class="pdf-td" style="width:100px;">{{ selectedTemplate === 'coated' ? baseInfo.level : corrugatedLevel }}</td>
            </tr>
          </table>
          <!-- 检测项目表格，包含标称定量行和实测数据表头、数据区 -->
          <table style="width:100%;border-collapse:collapse;font-size:14px;margin-top:8px;table-layout:fixed;">
            <tr>
              <th class="pdf-th" style="width:80px;" rowspan="2">指标名称</th>
              <th class="pdf-th" style="width:75px;" rowspan="2">单位</th>
              <th class="pdf-th" style="width:65px;" rowspan="2">标准</th>
              <th v-for="(group, idx) in getAllWeightGroupsSorted()" :key="'denval'+group.id" class="pdf-th" style="width:auto;">{{ group.weight ? group.weight + 'g' : '' }}</th>
            </tr>
            <tr>
              <th class="pdf-th" :colspan="getAllWeightGroupsSorted().length" style="text-align:center;">实测数据</th>
            </tr>
            <!-- 检测项目数据行，支持特殊项目多行合并 -->
            <template v-for="(row, ridx) in pdfRows" :key="'row'+ridx">
              <tr v-if="!row.isMultiRow">
                <td class="pdf-td" style="width:80px;">
                  <div v-if="row.name === '横向耐折度'">
                    <div>耐折度</div>
                    <div>(横向)</div>
                  </div>
                  <div v-else-if="row.name === '吸水性（正面）'">
                    <div>吸水性</div>
                    <div>（正面）</div>
                  </div>
                  <div v-else-if="row.name === '吸水性（反面）'">
                    <div>吸水性</div>
                    <div>（反面）</div>
                  </div>
                  <div v-else style="white-space: nowrap;">{{ row.name }}</div>
                </td>
                <td class="pdf-td" style="width:75px;">{{ row.unit }}</td>
                <td class="pdf-td" style="width:65px;white-space: nowrap;">{{ row.standard }}</td>
                <td v-for="(group, gidx) in getAllWeightGroupsSorted()" :key="'cell'+gidx" class="pdf-td" style="width:auto;">
                  {{ (() => {
                    const item = group.items.find(i => i.name === row.name);
                    return item ? (item.value || '-') : '-';
                  })() }}
                </td>
              </tr>
              <template v-else>
                <!-- 横向环压指数每个组一行，按克重排序 -->
                <tr v-for="(group, gidx) in getAllWeightGroupsSorted()" :key="'rct-'+gidx">
                  <td v-if="gidx===0" class="pdf-td" style="width:80px;" :rowspan="getAllWeightGroupsSorted().length">
                    <div>环压指数</div>
                    <div>(横向)</div>
                  </td>
                  <td v-if="gidx===0" class="pdf-td" style="width:75px;" :rowspan="getAllWeightGroupsSorted().length">{{ row.unit }}</td>
                  <td class="pdf-td" style="width:65px;white-space: nowrap;">{{ getRCTStandard(group) }}</td>
                  <td v-for="(targetGroup, tgidx) in getAllWeightGroupsSorted()" :key="'rctval-'+tgidx" class="pdf-td" style="width:auto;">
                    {{ targetGroup.id === group.id ? (() => {
                      const item = group.items.find(i => i.name === '横向环压指数');
                      return item ? (item.value || '-') : '-';
                    })() : '/' }}
                  </td>
                </tr>
              </template>
            </template>
          </table>
          <!-- 结论行用表格，印章盖在结论单元格上方 -->
          <div style="position:relative;margin-top:16px;">
            <table style="width:100%;border-collapse:collapse;font-size:15px;table-layout:fixed;">
              <tr class="conclusion-table">
                <td class="pdf-td" style="width:254px;font-weight:bold;height:90px;vertical-align:middle;">结论</td>
                <td class="pdf-td" style="width:calc(100% - 254px);text-align:center;position:relative;height:90px;vertical-align:middle;">
                  <span style="display:inline-block;width:100%;">{{ conclusion === '批次合格' ? '批次合格' : (conclusion === '不合格' ? '批次不合格' : conclusion) }}</span>
                  <img v-if="useSeal" src="/seal.png" style="position:absolute;top:calc(50% - 5px);left:calc(50% - 10px);transform:translate(-50%,-50%) rotate(-5deg);width:auto;height:auto;max-width:193.6px;opacity:0.8;z-index:2;" />
                </td>
              </tr>
            </table>
          </div>
          
          <!-- 签名区域 -->
          <div style="margin-top:30px;display:flex;justify-content:space-between;align-items:center;font-size:14px;">
            <div style="text-align:left;">
              <span style="font-weight:bold;">检验：</span>
              <div v-if="signatureData.inspector.signature" style="display:inline-block;max-width:180px;max-height:45px;vertical-align:middle;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;pointer-events:none;" @contextmenu.prevent @dragstart.prevent>
                <div v-html="getSignatureContent(signatureData.inspector.signature)" style="max-width:100%;max-height:100%;"></div>
              </div>
              <span v-else>{{ signatureData.inspector.name }}</span>
            </div>
            <div style="text-align:center;flex:1;margin:0 20px;">
              <span style="font-weight:bold;">审核：</span>
              <div v-if="signatureData.reviewer.signature" style="display:inline-block;max-width:180px;max-height:45px;vertical-align:middle;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;pointer-events:none;" @contextmenu.prevent @dragstart.prevent>
                <div v-html="getSignatureContent(signatureData.reviewer.signature)" style="max-width:100%;max-height:100%;"></div>
              </div>
              <span v-else>{{ signatureData.reviewer.name }}</span>
            </div>
            <div style="text-align:right;width:120px;">
              <!-- 预留空间保持布局平衡 -->
            </div>
          </div>
          
          <!-- 注释 -->
          <div style="font-size:12px;color:#222;margin-top:18px;text-align:left;">
            注：检测环境：23±1℃，50±2%RH；相关指标均按国家标准进行检测，带*为参考指标。
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-tooltip 
          content="请先完成编辑" 
          placement="top" 
          :disabled="!isEditing"
        >
          <el-button type="primary" @click="generatePDF(true)" :disabled="isEditing">导出PDF</el-button>
        </el-tooltip>
      </div>
    </template>
  </el-dialog>

  <!-- PDF专用模板div，完善为与截图一致结构 -->
  <div v-if="pdfVisible" ref="pdfRef" class="pdf-report-template" style="
    width: 210mm;
    height: 297mm;
    padding: 1.5cm;
    box-sizing: border-box;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 9999;
    background: #fff;
    border: 1px solid #ccc;
  ">
    <div style="width:100%;height:100%;">
             <!-- 公司名、标题、LOGO -->
       <div style="display:flex;align-items:center;justify-content:space-between;">
                   <div style="width:90px;height:60px;display:flex;align-items:center;justify-content:center;">
            <img src="/logo.png" style="max-width:100%;max-height:100%;object-fit:contain;" />
          </div>
         <div style="flex:1;text-align:center;margin:0 16px;">
           <div style="font-size:22px;font-weight:bold;">唐山市冀滦纸业有限公司</div>
           <div style="font-size:18px;margin-top:2px;">出厂检验报告</div>
         </div>
         <div style="width:90px;height:60px;"></div>
       </div>
      <!-- 报告日期和报告编号行 -->
       <div style="display:flex;justify-content:space-between;align-items:center;font-size:14px;margin:8px 0 0 0;">
        <span>报告编号：{{ generateReportCode() }}</span>
         <span>报告日期：{{ baseInfo.date }}</span>
       </div>
             <!-- 信息区表格（客户名称、车牌号、产品名称、产品等级） -->
               <table style="width:100%;border-collapse:collapse;font-size:14px;margin-top:8px;">
          <tr>
            <td class="pdf-td" style="width:39px;">客户名称</td>
            <td class="pdf-td" style="width:83px;">{{ baseInfo.customer }}</td>
            <td class="pdf-td" style="width:100px;">车牌号</td>
            <td class="pdf-td" style="width:100px;">{{ baseInfo.plate }}</td>
          </tr>
          <tr>
            <td class="pdf-td" style="width:39px;">产品名称</td>
            <td class="pdf-td" style="width:83px;">{{ baseInfo.product }}</td>
            <td class="pdf-td" style="width:100px;">产品等级</td>
            <td class="pdf-td" style="width:100px;">{{ selectedTemplate === 'coated' ? baseInfo.level : corrugatedLevel }}</td>
          </tr>
        </table>
             <!-- 检测项目表格，包含标称定量行和实测数据表头、数据区 -->
               <table style="width:100%;border-collapse:collapse;font-size:14px;margin-top:8px;table-layout:fixed;">
                   <tr>
                        <th class="pdf-th" style="width:80px;" rowspan="2">指标名称</th>
              <th class="pdf-th" style="width:75px;" rowspan="2">单位</th>
              <th class="pdf-th" style="width:65px;" rowspan="2">标准</th>
                       <th v-for="(group, idx) in getAllWeightGroupsSorted()" :key="'denval'+group.id" class="pdf-th" style="width:auto;">{{ group.weight ? group.weight + 'g' : '' }}</th>
          </tr>
         <tr>
                      <th class="pdf-th" :colspan="getAllWeightGroupsSorted().length" style="text-align:center;">实测数据</th>
         </tr>
                  <!-- 检测项目数据行，支持特殊项目多行合并 -->
          <template v-for="(row, ridx) in pdfRows" :key="'row'+ridx">
                        <tr v-if="!row.isMultiRow">
               <td class="pdf-td" style="width:80px;">
                 <div v-if="row.name === '横向耐折度'">
                   <div>耐折度</div>
                   <div>(横向)</div>
                 </div>
                 <div v-else-if="row.name === '吸水性（正面）'">
                   <div>吸水性</div>
                   <div>（正面）</div>
                 </div>
                 <div v-else-if="row.name === '吸水性（反面）'">
                   <div>吸水性</div>
                   <div>（反面）</div>
                 </div>
                 <div v-else style="white-space: nowrap;">{{ row.name }}</div>
               </td>
               <td class="pdf-td" style="width:75px;">{{ row.unit }}</td>
                             <td class="pdf-td" style="width:65px;white-space: nowrap;">{{ row.standard }}</td>
                             <td v-for="(group, gidx) in getAllWeightGroupsSorted()" :key="'cell'+gidx" class="pdf-td" style="width:auto;">
                 {{ (() => {
                   const item = group.items.find(i => i.name === row.name);
                   return item ? (item.value || '-') : '-';
                 })() }}
               </td>
            </tr>
                        <template v-else>
                              <!-- 横向环压指数每个组一行，按克重排序 -->
                                <tr v-for="(group, gidx) in getAllWeightGroupsSorted()" :key="'rct-'+gidx">
                   <td v-if="gidx===0" class="pdf-td" style="width:80px;" :rowspan="getAllWeightGroupsSorted().length">
                     <div>环压指数</div>
                     <div>(横向)</div>
                   </td>
                  <td v-if="gidx===0" class="pdf-td" style="width:75px;" :rowspan="getAllWeightGroupsSorted().length">{{ row.unit }}</td>
                                   <td class="pdf-td" style="width:65px;white-space: nowrap;">{{ getRCTStandard(group) }}</td>
                  <td v-for="(targetGroup, tgidx) in getAllWeightGroupsSorted()" :key="'rctval-'+tgidx" class="pdf-td" style="width:auto;">
                   {{ targetGroup.id === group.id ? (() => {
                     const item = group.items.find(i => i.name === '横向环压指数');
                     return item ? (item.value || '-') : '-';
                   })() : '/' }}
                 </td>
               </tr>
             </template>
          </template>
       </table>
                           <!-- 结论行用表格，印章盖在结论单元格上方 -->
                <div style="position:relative;margin-top:16px;">
                      <table style="width:100%;border-collapse:collapse;font-size:15px;table-layout:fixed;">
                          <tr class="conclusion-table">
                             <td class="pdf-td" style="width:254px;font-weight:bold;height:90px;vertical-align:middle;">结论</td>
                                 <td class="pdf-td" style="width:calc(100% - 254px);text-align:center;position:relative;height:90px;vertical-align:middle;">
                                 <span style="display:inline-block;width:100%;">{{ conclusion === '批次合格' ? '批次合格' : (conclusion === '不合格' ? '批次不合格' : conclusion) }}</span>
                  <img v-if="useSeal" src="/seal.png" style="position:absolute;top:calc(50% - 5px);left:calc(50% - 10px);transform:translate(-50%,-50%) rotate(-5deg);width:auto;height:auto;max-width:193.6px;opacity:0.8;z-index:2;" />
                </td>
             </tr>
          </table>
        </div>
      
      <!-- 注释 -->
      <div style="font-size:12px;color:#222;margin-top:18px;text-align:left;">
        注：检测环境：23±1℃，50±2%RH；相关指标均按国家标准进行检测，带*为参考指标。
      </div>
      
      <!-- 签名区域 -->
      <div style="margin-top:30px;display:flex;justify-content:space-between;align-items:center;font-size:14px;">
        <div style="text-align:left;">
          <span style="font-weight:bold;">检验：</span>
          <div v-if="signatureData.inspector.signature" style="display:inline-block;max-width:180px;max-height:45px;vertical-align:middle;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;pointer-events:none;" @contextmenu.prevent @dragstart.prevent>
            <div v-html="getSignatureContent(signatureData.inspector.signature)" style="max-width:100%;max-height:100%;"></div>
          </div>
          <span v-else>{{ signatureData.inspector.name }}</span>
        </div>
        <div style="text-align:center;flex:1;margin:0 20px;">
          <span style="font-weight:bold;">审核：</span>
          <div v-if="signatureData.reviewer.signature" style="display:inline-block;max-width:180px;max-height:45px;vertical-align:middle;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;pointer-events:none;" @contextmenu.prevent @dragstart.prevent>
            <div v-html="getSignatureContent(signatureData.reviewer.signature)" style="max-width:100%;max-height:100%;"></div>
          </div>
          <span v-else>{{ signatureData.reviewer.name }}</span>
        </div>
        <div style="text-align:right;width:120px;">
          <!-- 预留空间保持布局平衡 -->
        </div>
      </div>
    </div>
  </div>

<!-- 技术标准维护对话框 -->

  <!-- 签名管理对话框 -->
  <el-dialog
    v-model="signatureDialogVisible"
    title="签名管理"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="signature-dialog"
  >
    <SignatureManage ref="signatureManageRef" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="signatureDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="saveSignatureSettings">保存设置</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, watch, computed, nextTick, onMounted, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import AV from '../leancloud'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'
import SignatureManage from './SignatureManage.vue'

const route = useRoute()
const router = useRouter()

function safeClone(arr) {
  return JSON.parse(JSON.stringify(Array.isArray(arr) ? arr : []))
}

// 判断签名类型并返回相应的渲染内容
function getSignatureContent(signature) {
  if (!signature) return ''
  
  // 只支持SVG代码（包含<svg标签）
  if (signature.includes('<svg')) {
    return signature
  }
  
  // 其他情况返回空字符串
  return ''
}

// 删除默认模板定义，完全依赖技术标准库
// const rctStandardAAA = { 80: '≥3.0', 85: '≥3.5', 90: '≥4.5', 95: '≥5.0', 100: '≥6.0', 105: '≥6.5', 110: '≥7.0', 115: '≥7.0', 120: '≥7.5', 125: '≥7.5', 130: '≥8.0', 140: '≥8.5' }
// const rctStandardA = { 80: '≥3.0', 85: '≥3.5', 90: '≥4.0', 95: '≥4.5', 100: '≥5.0', 105: '≥5.0', 110: '≥5.0', 115: '≥5.2', 120: '≥6.0', 125: '≥6.5', 130: '≥7.0', 140: '≥7.0' }

// const templates = {
//   coated: [
//     { name: '定量', unit: 'g/m²', standard: '+3/-5', value: '', result: '' },
//     { name: '水份', unit: '%', standard: '8.5±2', value: '', result: '' },
//     { name: '紧度', unit: 'g/cm³', standard: '≥0.7', value: '', result: '' },
//     { name: '横向耐折度', unit: '次', standard: '≥10', value: '', result: '' },
//     { name: '耐破指数', unit: 'kpa·m²/g', standard: '≥1.8', value: '', result: '' },
//     { name: '横向环压指数', unit: 'N·m/g', standard: '≥6.5', value: '', result: '' },
//     { name: '吸水性（正面）', unit: 'g/m²', standard: '≤80', value: '', result: '' },
//     { name: '吸水性（反面）', unit: 'g/m²', standard: '≤130', value: '', result: '' },
//   ],
//   corrugated: {
//     'AAA级': [
//       { name: '定量', unit: 'g/m²', standard: '+3/-5', value: '', result: '' },
//       { name: '水份', unit: '%', standard: '8±2', value: '', result: '' },
//       { name: '紧度', unit: 'g/cm³', standard: '≥0.55', value: '', result: '' },
//       { name: '横向环压指数', unit: 'N·m/g', standard: '', value: '', result: '' },
//       { name: '吸水性', unit: 'g/m²', standard: '≤60', value: '', result: '' },
//       { name: '裂断长', unit: 'km', standard: '≥4.2', value: '', result: '' },
//       { name: '抗冷水', unit: 'S', standard: '≥600', value: '', result: '' },
//     ],
//     'A级': [
//       { name: '定量', unit: 'g/m²', standard: '+3/-5', value: '', result: '' },
//       { name: '水份', unit: '%', standard: '8±2', value: '', result: '' },
//       { name: '紧度', unit: 'g/cm³', standard: '≥0.55', value: '', result: '' },
//       { name: '横向环压指数', unit: 'N·m/g', standard: '', value: '', result: '' },
//       { name: '吸水性', unit: 'g/m²', standard: '≤80', value: '', result: '' },
//     ]
//   }
// }
const selectedTemplate = ref('coated')
const corrugatedLevel = ref('A级')
const baseInfo = ref({ 
  date: '', // 初始为空，在resetReportForm中设置当前日期
  customer: '', 
  plate: '', 
  product: '滦星牌箱板纸', 
  level: '一级',
  reportCode: '',
  firstSavedAt: ''
})

// 表单验证规则
const formRules = computed(() => ({
  date: [
    { required: true, message: '请选择报告日期', trigger: 'change' }
  ],
  customer: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  plate: [
    { required: true, message: '请输入车牌号', trigger: 'blur' }
  ],
  template: [
    { validator: validateTemplate, trigger: 'change' }
  ],
  level: [
    { required: true, message: '请输入产品等级', trigger: 'blur' }
  ],
  corrugatedLevel: [
    { required: true, message: '请选择产品等级', trigger: 'change' }
  ]
}))

const baseFormRef = ref(null)

// 自定义验证函数 - 验证模板选择
const validateTemplate = (rule, value, callback) => {
  if (!selectedTemplate.value) {
    callback(new Error('请选择产品模板'))
  } else {
    callback()
  }
}

// 创建包含所有表单数据的对象
const formData = computed(() => ({
  ...baseInfo.value,
  template: selectedTemplate.value,
  corrugatedLevel: corrugatedLevel.value
}))

const weightGroups = ref([
  { id: 1, weight: '', items: [] } // 初始化时items为空，由updateGroupStandardByWeight填充
])
let groupId = 2
const MAX_GROUPS = 4;
const useSeal = ref(false);

// 签名相关变量
const signatureDialogVisible = ref(false)
const signatureManageRef = ref(null)
const signatureData = ref({
  inspector: {
    name: localStorage.getItem('currentUsername') || '未知用户',
    signature: '',
    style: 'handwritten'
  },
  reviewer: {
    name: '姚俊磊',
    signature: '',
    style: 'handwritten'
  }
})

// ====== 技术标准自动引用增强 begin ======
// 添加标志防止循环更新
let isUpdatingStandards = false

function getCurrentGrade() {
  if (selectedTemplate.value === 'corrugated') {
    return corrugatedLevel.value || 'AAA级'
  } else {
    // 箱板纸等级映射：一级 -> 一级品
    const level = baseInfo.value.level || '一级'
    const levelMapping = {
      '一级': '一级品',
      '二级': '二级品'
    }
    return levelMapping[level] || level
  }
}

// 纸种名称映射：英文 -> 中文
function getPaperTypeName(englishName) {
  const mapping = {
    'coated': '箱板纸',
    'corrugated': '高强瓦楞原纸'
  }
  return mapping[englishName] || englishName
}

function getStandardItems(paperType, weight, grade) {
  const raw = localStorage.getItem('factory_standard_versions')
  if (!raw) return null
  let data
  try { data = JSON.parse(raw) } catch (e) {
    return null 
  }
  
  // 将英文纸种名称转换为中文
  const chinesePaperType = getPaperTypeName(paperType)
  
  const versions = data[chinesePaperType]
  if (!versions || !versions.length) {
    return null
  }
  const version = versions[versions.length - 1]
  
  // 如果weight为空，返回该纸种和等级的第一个克重的指标作为模板
  if (!weight) {
    const firstWeightItem = version.data.find(w => w.weight)
    if (!firstWeightItem) {
      return null
    }
    
    const gradeItem = firstWeightItem.grades.find(g => g.grade == grade)
    if (!gradeItem) {
      return null
    }
    return gradeItem.items.map(i => ({
      name: i.name,
      unit: i.unit,
      standard: '', // 模板时标准为空，等填入克重后再填充
      value: '',
      result: ''
    }))
  }
  
  // 如果weight不为空，查找特定克重的数据
  const weightItem = version.data.find(w => w.weight == weight)
  if (!weightItem) {
    return null
  }
  const gradeItem = weightItem.grades.find(g => g.grade == grade)
  if (!gradeItem) {
    return null
  }
  return gradeItem.items.map(i => ({
    name: i.name,
    unit: i.unit,
    standard: i.standard,
    value: '',
    result: ''
  }))
}
function updateGroupStandardByWeight(group) {
  if (!group.weight || isUpdatingStandards) return
  
  isUpdatingStandards = true
  try {
    const stdItems = getStandardItems(
      selectedTemplate.value,
      group.weight,
      getCurrentGrade()
    )
    if (stdItems && stdItems.length) {
      stdItems.forEach(item => {
        const old = group.items.find(i => i.name === item.name)
        if (old) {
          item.value = old.value
          item.result = old.result
        }
      })
      group.items = stdItems
      
      // 更新标准后，对已有数据进行判定
      group.items.forEach(item => {
        if (item.value) {
          judgeItem(item, group)
        }
      })
    } else {
      ElMessage.warning(`未找到${group.weight}g的${selectedTemplate.value}技术标准，请检查标准库。`);
      group.items = []; // 如果没有标准，清空项目
    }
  } finally {
    isUpdatingStandards = false
  }
}
// ====== 技术标准自动引用增强 end ======

// ====== 历史记录功能 begin ======
// 客户名称历史记录
function queryCustomerHistory(queryString, cb) {
  const history = getCustomerHistory()
  const results = queryString 
    ? history.filter(item => item.value.toLowerCase().includes(queryString.toLowerCase()))
    : history
  // 确保返回的数据格式正确，避免 Element Plus 警告
  cb(results || [])
}

function saveCustomerHistory() {
  if (!baseInfo.value.customer || !isEditing.value) return
  const history = getCustomerHistory()
  const newItem = { 
    value: baseInfo.value.customer.trim(),
    label: baseInfo.value.customer.trim() // 添加 label 属性以确保兼容性
  }
  
  // 如果已存在，先移除旧的
  const index = history.findIndex(item => item.value === newItem.value)
  if (index > -1) {
    history.splice(index, 1)
  }
  
  // 添加到开头
  history.unshift(newItem)
  
  // 只保留最近20条记录
  if (history.length > 20) {
    history.splice(20)
  }
  
  localStorage.setItem('customer_history', JSON.stringify(history))
}

function getCustomerHistory() {
  try {
    const history = JSON.parse(localStorage.getItem('customer_history') || '[]')
    // 验证和清理数据格式
    return history.filter(item => {
      return item && typeof item === 'object' && 
             typeof item.value === 'string' && 
             item.value.trim() !== ''
    }).map(item => ({
      value: item.value.trim(),
      label: item.label || item.value.trim()
    }))
  } catch {
    return []
  }
}

function onCustomerSelect(item) {
  baseInfo.value.customer = item.value
}

// 删除客户名称历史记录
function deleteCustomerHistory(customerName) {
  ElMessageBox.confirm(
    `确定要删除客户"${customerName}"的历史记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const history = getCustomerHistory()
    const filteredHistory = history.filter(item => item.value !== customerName)
    localStorage.setItem('customer_history', JSON.stringify(filteredHistory))
    
    // 如果删除的是当前输入的值，清空输入框
    if (baseInfo.value.customer === customerName) {
      baseInfo.value.customer = ''
    }
    
    ElMessage.success('客户记录已删除')
  }).catch(() => {
    // 用户取消删除
  })
}

// 车牌号历史记录
function queryPlateHistory(queryString, cb) {
  const history = getPlateHistory()
  const results = queryString 
    ? history.filter(item => item.value.toLowerCase().includes(queryString.toLowerCase()))
    : history
  // 确保返回的数据格式正确，避免 Element Plus 警告
  cb(results || [])
}

function savePlateHistory() {
  if (!baseInfo.value.plate || !isEditing.value) return
  const history = getPlateHistory()
  const newItem = { 
    value: baseInfo.value.plate.trim(),
    label: baseInfo.value.plate.trim() // 添加 label 属性以确保兼容性
  }
  
  // 如果已存在，先移除旧的
  const index = history.findIndex(item => item.value === newItem.value)
  if (index > -1) {
    history.splice(index, 1)
  }
  
  // 添加到开头
  history.unshift(newItem)
  
  // 只保留最近20条记录
  if (history.length > 20) {
    history.splice(20)
  }
  
  localStorage.setItem('plate_history', JSON.stringify(history))
}

function getPlateHistory() {
  try {
    const history = JSON.parse(localStorage.getItem('plate_history') || '[]')
    // 验证和清理数据格式
    return history.filter(item => {
      return item && typeof item === 'object' && 
             typeof item.value === 'string' && 
             item.value.trim() !== ''
    }).map(item => ({
      value: item.value.trim(),
      label: item.label || item.value.trim()
    }))
  } catch {
    return []
  }
}

function onPlateSelect(item) {
  baseInfo.value.plate = item.value
}

// 删除车牌号历史记录
function deletePlateHistory(plateNumber) {
  ElMessageBox.confirm(
    `确定要删除车牌号"${plateNumber}"的历史记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const history = getPlateHistory()
    const filteredHistory = history.filter(item => item.value !== plateNumber)
    localStorage.setItem('plate_history', JSON.stringify(filteredHistory))
    
    // 如果删除的是当前输入的值，清空输入框
    if (baseInfo.value.plate === plateNumber) {
      baseInfo.value.plate = ''
    }
    
    ElMessage.success('车牌记录已删除')
  }).catch(() => {
    // 用户取消删除
  })
}
// ====== 历史记录功能 end ======

// 清理历史记录中的无效数据
function cleanupHistoryData() {
  try {
    // 清理客户历史记录
    const customerHistory = JSON.parse(localStorage.getItem('customer_history') || '[]')
    const validCustomerHistory = customerHistory.filter(item => {
      return item && typeof item === 'object' && 
             typeof item.value === 'string' && 
             item.value.trim() !== ''
    }).map(item => ({
      value: item.value.trim(),
      label: item.value.trim()
    }))
    localStorage.setItem('customer_history', JSON.stringify(validCustomerHistory))
    
    // 清理车牌历史记录
    const plateHistory = JSON.parse(localStorage.getItem('plate_history') || '[]')
    const validPlateHistory = plateHistory.filter(item => {
      return item && typeof item === 'object' && 
             typeof item.value === 'string' && 
             item.value.trim() !== ''
    }).map(item => ({
      value: item.value.trim(),
      label: item.value.trim()
    }))
    localStorage.setItem('plate_history', JSON.stringify(validPlateHistory))
  } catch (error) {
    console.warn('清理历史记录数据时出错:', error)
  }
}

// 页面加载时自动初始化
onMounted(() => {
  // 清理过期的报告计数器
  cleanupExpiredCounters()
  
  // 清理历史记录中的无效数据
  cleanupHistoryData()
  
  // 加载签名数据
  loadSignatureData()
  
  // 如果是新建报告页面，确保重置表单
  if (route.path === '/factory-report/new') {
    nextTick(() => {
      resetReportForm()
    })
  }
  
  const reportId = route.params.id
  if (reportId && reportId !== 'new') {
    loadReport(reportId)
  } else {
    // 新建模式 - 调用resetReportForm确保设置当前日期
    resetReportForm()
  }
  
  // 自动加载第一个克重组的技术标准
  if (weightGroups.value.length > 0) {
    updateGroupStandardByWeight(weightGroups.value[0])
  }
})

function addWeightGroup() {
  if (weightGroups.value.length >= MAX_GROUPS) {
    ElMessage.warning(`每张报告最多只能添加${MAX_GROUPS}个克重组！`);
    return;
  }
  let templateData = []
  const stdItems = getStandardItems(
    selectedTemplate.value,
    '', // 新增时还没填克重
    getCurrentGrade()
  )
  if (stdItems && stdItems.length) {
    templateData = stdItems
  } else {
    ElMessage.warning(`未找到${selectedTemplate.value}模板的技术标准，请检查标准库。`);
    templateData = []; // 如果没有模板标准，清空项目
  }
  weightGroups.value.push({
    id: groupId++,
    weight: '',
    items: safeClone(templateData)
  })
}
function removeWeightGroup(idx) {
  weightGroups.value.splice(idx, 1)
}
// 删除updateGroupRCTStandard函数，完全依赖技术标准库
// function updateGroupRCTStandard(group) {
//   if (selectedTemplate.value !== 'corrugated') return
//   const rctItem = group.items.find(i => i.name === '横向环压指数')
//   if (!rctItem || rctItem.standard) return // 如果已有标准值，不覆盖
//   
//   const weight = parseInt(group.weight)
//   const rctMap = corrugatedLevel.value === 'AAA级' ? rctStandardAAA : rctStandardA
//   let closest = Object.keys(rctMap).map(Number).reduce((prev, curr) => {
//     return (weight >= curr && curr > prev) ? curr : prev
//   }, 80)
//   const std = rctMap[closest] || ''
//   if (rctItem) rctItem.standard = std
// }
function onTemplateChange() {
  let templateData = []
  // 优先使用技术标准库
  const stdItems = getStandardItems(
    selectedTemplate.value,
    '', // 切换模板时还没填克重
    getCurrentGrade()
  )
  if (stdItems && stdItems.length) {
    templateData = stdItems
  } else {
    ElMessage.warning(`未找到${selectedTemplate.value}模板的技术标准，请检查标准库。`);
    templateData = []; // 如果没有模板标准，清空项目
  }
  
  weightGroups.value = [
    { id: 1, weight: '', items: safeClone(templateData) }
  ]
  baseInfo.value.product = selectedTemplate.value === 'coated' ? '滦星牌箱板纸' : '滦月牌高强瓦楞原纸'
  groupId = 2
}
function onCorrugatedLevelChange() {
  weightGroups.value.forEach(group => {
    // 优先使用技术标准库
    const stdItems = getStandardItems(
      selectedTemplate.value,
      group.weight,
      getCurrentGrade()
    )
    if (stdItems && stdItems.length) {
      // 保留用户已输入的值
      stdItems.forEach(item => {
        const old = group.items.find(i => i.name === item.name)
        if (old) {
          item.value = old.value
          item.result = old.result
        }
      })
      group.items = stdItems
      
      // 更新标准后，对已有数据进行判定
      group.items.forEach(item => {
        if (item.value) {
          judgeItem(item, group)
        }
      })
    } else {
      ElMessage.warning(`未找到${group.weight}g的${selectedTemplate.value}技术标准，请检查标准库。`);
      group.items = []; // 如果没有标准，清空项目
    }
  })
}
// 合并监听器，避免循环更新
watch(weightGroups.value, (groups) => {
  if (isUpdatingStandards) return // 如果正在更新标准，跳过判定
  
  groups.forEach(group => {
    // 只进行判定，不更新标准
    group.items.forEach(item => judgeItem(item, group))
  })
}, { deep: true })



function judgeItem(item, group) {
  if (!item.value) { item.result = ''; return; }
  const v = parseFloat(item.value)
  // 定量项目特殊判定
  if (item.name === '定量' && item.standard === '+3/-5') {
    const base = parseFloat(group.weight)
    if (!isNaN(base) && !isNaN(v)) {
      item.result = (v >= base - 5 && v <= base + 3) ? '合格' : '不合格'
      return
    }
  }
  if (item.standard.includes('±')) {
    // 形如8.5±2
    const [base, delta] = item.standard.split('±').map(Number)
    if (!isNaN(base) && !isNaN(delta)) {
      item.result = (v >= base - delta && v <= base + delta) ? '合格' : '不合格'
      return
    }
  }
  if (item.standard.startsWith('≥')) {
    const min = parseFloat(item.standard.replace('≥', ''))
    item.result = v >= min ? '合格' : '不合格'
    return
  }
  if (item.standard.startsWith('≤')) {
    const max = parseFloat(item.standard.replace('≤', ''))
    item.result = v <= max ? '合格' : '不合格'
    return
  }
  item.result = ''
}

const conclusion = computed(() => {
  for (const group of weightGroups.value) {
    if (group.items.some(i => i.result === '不合格')) return '不合格'
  }
  if (weightGroups.value.every(group =>
    group.items.every(i => i.result === '合格' || !i.value)
  )) return '批次合格'
  return ''
})

// 计算同克重的编号，仅用于前端显示
function getDisplayWeight(group, idx) {
  const weight = group.weight;
  if (!weight) return '';
  // 找到所有相同克重的组
  const sameWeightGroups = weightGroups.value.filter(g => g.weight === weight);
  if (sameWeightGroups.length <= 1) return weight;
  
  // 按id排序，确定当前组的序号
  const sortedGroups = sameWeightGroups.sort((a, b) => a.id - b.id);
  const currentIndex = sortedGroups.findIndex(g => g.id === group.id);
  return `${weight}-${currentIndex + 1}`;
}

// 获取环压指数标准值（用于PDF显示）
function getRCTStandard(group) {
  // 从技术标准库获取环压指数标准
  const rctItem = group.items.find(i => i.name === '横向环压指数');
  if (rctItem && rctItem.standard) {
    return rctItem.standard;
  }
  return ''; // 如果没有找到标准，返回空
}

// 按克重排序分组，相同克重的组放在一起
function getSortedWeightGroups() {
  const weightMap = new Map();
  
  // 按克重分组
  weightGroups.value.forEach(group => {
    const weight = parseInt(group.weight) || 0;
    if (!weightMap.has(weight)) {
      weightMap.set(weight, []);
    }
    weightMap.get(weight).push(group);
  });
  
  // 按克重排序并返回分组
  return Array.from(weightMap.entries())
    .sort(([a], [b]) => a - b)
    .map(([weight, groups]) => ({
      weight,
      groups
    }));
}

// 获取排序后的克重列表，用于表头显示
function getSortedWeights() {
  return getSortedWeightGroups().map(wg => wg.weight);
}

// 获取指定克重的所有组
function getGroupsByWeight(weight) {
  return weightGroups.value.filter(g => parseInt(g.weight) === weight);
}

// 获取所有克重组，按克重排序，每个组一个列
function getAllWeightGroupsSorted() {
  const sortedGroups = [];
  const weightMap = new Map();
   
  // 按克重分组
  weightGroups.value.forEach(group => {
    const weight = parseInt(group.weight) || 0;
    if (!weightMap.has(weight)) {
      weightMap.set(weight, []);
    }
    weightMap.get(weight).push(group);
  });
   
  // 按克重排序，每个组都单独添加
  return Array.from(weightMap.entries())
    .sort(([a], [b]) => a - b)
    .flatMap(([weight, groups]) => groups);
}

// 生成报告编号（仅用于显示，不占用计数器）
function generateReportCode() {
  // 如果是已保存的报告，显示自己的编号
  if (isSaved.value && baseInfo.value.reportCode) {
    return baseInfo.value.reportCode;
  }
  
  // 如果是新建报告，显示下一个编号
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  
  // 从localStorage获取当日计数器，但不增加计数器
  const today = `${year}${month}${day}`;
  const storageKey = `reportCounter_${today}`;
  let counter = parseInt(localStorage.getItem(storageKey)) || 0;
  
  // 确保计数器有效（0-999范围内）
  if (counter < 0 || counter > 999) {
    counter = 0;
    localStorage.setItem(storageKey, '0');
  }
  
  // 格式：JL-YYYYMMDD-XXX（JL-年月日-3位序号，从001开始）
  return `JL-${year}${month}${day}-${(counter + 1).toString().padStart(3, '0')}`;
}

// 预分配报告编号（在保存前调用）
function preAllocateReportCode() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  
  const today = `${year}${month}${day}`;
  const storageKey = `reportCounter_${today}`;
  let counter = parseInt(localStorage.getItem(storageKey)) || 0;
  
  // 确保计数器有效（0-999范围内）
  if (counter < 0 || counter > 999) {
    counter = 0;
  }
  
  counter++;
  
  // 保存更新后的计数器
  localStorage.setItem(storageKey, counter.toString());
  
  return `JL-${year}${month}${day}-${counter.toString().padStart(3, '0')}`;
}

// 回滚报告编号（保存失败时调用）
function rollbackReportCode() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  
  const today = `${year}${month}${day}`;
  const storageKey = `reportCounter_${today}`;
  let counter = parseInt(localStorage.getItem(storageKey)) || 0;
  
  // 确保计数器不会小于0
  counter = Math.max(0, counter - 1);
  
  // 保存更新后的计数器
  localStorage.setItem(storageKey, counter.toString());
}

// 清理过期的报告计数器（保留最近30天的数据）
function cleanupExpiredCounters() {
  const now = new Date();
  const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
  
  // 遍历localStorage中的所有reportCounter键
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    if (key && key.startsWith('reportCounter_')) {
      const dateStr = key.replace('reportCounter_', '');
      
      // 解析日期字符串
      if (dateStr.length === 8) {
        const year = parseInt(dateStr.substring(0, 4));
        const month = parseInt(dateStr.substring(4, 6)) - 1; // 月份从0开始
        const day = parseInt(dateStr.substring(6, 8));
        const date = new Date(year, month, day);
        
        // 如果日期超过30天，删除该计数器
        if (date < thirtyDaysAgo) {
          localStorage.removeItem(key);
        }
      }
    }
  }
}





// 生成横向多克重表格数据
const pdfRows = computed(() => {
  if (!weightGroups.value.length || !weightGroups.value[0].items) return [];
  const templateItems = weightGroups.value[0].items;
  const multiRowProjects = ['环压指数(横向)','横向环压指数'];
  let rows = [];
  
  for (let idx = 0; idx < templateItems.length; idx++) {
    const tmpl = templateItems[idx];
    if (!tmpl) continue;
    
    if (multiRowProjects.includes(tmpl.name)) {
      // 横向环压指数按克重分组显示
      rows.push({
        name: tmpl.name,
        unit: tmpl.unit,
        standard: '', // 标准会在模板中根据每个克重动态显示
        isMultiRow: true
      });
    } else {
      // 普通项目一行横向展开
      rows.push({
        name: tmpl.name,
        unit: tmpl.unit,
        standard: tmpl.standard,
        isMultiRow: false
      });
    }
  }
  return rows;
});

const pdfRef = ref(null)
const pdfVisible = ref(false)
const previewRef = ref(null)
const previewVisible = ref(false)

const isSaved = ref(false)
const isEditing = ref(true)

// 添加标准快照响应式变量
const standardSnapshot = ref(null)

// 添加获取当前标准版本号的函数
function getCurrentStandardVersionId() {
  // 从localStorage获取当前标准版本号
  const raw = localStorage.getItem('factory_standard_versions')
  if (!raw) return undefined
  
  try {
    const data = JSON.parse(raw)
    // 根据当前选择的模板获取版本号
    const paperType = getPaperTypeName(selectedTemplate.value)
    const versions = data[paperType]
    if (versions && versions.length > 0) {
      const latestVersion = versions[versions.length - 1]
      // 标准版本数据使用 id 字段
      return latestVersion.id || latestVersion.version || latestVersion.versionId || latestVersion.name || undefined
    }
  } catch (e) {
    console.error('解析标准版本数据失败:', e)
  }
  return undefined
}





function showPreview() {
  // 检查是否正在编辑状态
  if (isEditing.value) {
    ElMessage.warning('请先完成编辑后再预览报告');
    return;
  }
  
  // 确保签名数据是最新的
  loadSignatureData()
  
  // 验证基本信息表单
  if (baseFormRef.value) {
    try {
      baseFormRef.value.validate();
    } catch (error) {
      ElMessage.error('请完善基本信息');
      return;
    }
  }
  
  // 验证克重信息
  if (!weightGroups.value.length || weightGroups.value.some(group => !group.weight)) {
    ElMessage.error('请填写所有克重信息');
    return;
  }
  
  // 验证检测数据
  for (const group of weightGroups.value) {
    for (const item of group.items) {
      if (!item.value && item.name !== '横向环压指数') {
        ElMessage.error(`请填写${group.weight}g的${item.name}检测数据`);
        return;
      }
    }
  }
  
  // 显示预览对话框
  previewVisible.value = true;
}

function goToList() {
  router.push('/factory-report')
}

function goToStandardMaintain() {
  router.push('/standard-maintain')
}

function goToNewReport() {
  // 无论当前在哪个页面，都强制跳转到新建报告页面
  // 这样可以确保状态完全重置
  router.push('/factory-report/new').then(() => {
    // 确保路由跳转完成后再重置表单
    nextTick(() => {
      resetReportForm()
    })
  });
}

// 重置表单内容的函数
function resetReportForm() {
  // 重置模板选择
  selectedTemplate.value = 'coated'
  corrugatedLevel.value = 'A级'
  
  // 使用更可靠的方式获取当前日期，不受时区影响
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const currentDate = `${year}-${month}-${day}`
  
  // 重置基本信息
  baseInfo.value = {
    date: currentDate,
    customer: '',
    plate: '',
    product: '滦星牌箱板纸',
    level: '一级',
    reportCode: '',
    firstSavedAt: '',
    inspectorName: '' // 重置检验员信息
  }
  
  // 重置克重组
  weightGroups.value = [
    { id: 1, weight: '', items: [] }
  ]
  groupId = 2
  
  // 重置其他状态
  useSeal.value = false
  isEditing.value = true
  isSaved.value = false
  
  // 清空标准快照
  standardSnapshot.value = null
  
  // 重置表单验证状态
  if (baseFormRef.value) {
    baseFormRef.value.clearValidate()
  }
  
  // 强制更新视图
  nextTick(() => {
    // 确保所有响应式数据都已更新
  })
}

// 页面初始化和路由变化时自动重置
watch(
  () => route.path,
  (newPath, oldPath) => {
    if (newPath === '/factory-report/new') {
      // 如果是从其他页面跳转到新建页面，强制重置
      if (oldPath && oldPath !== '/factory-report/new') {
        nextTick(() => {
          resetReportForm()
        })
      } else {
      resetReportForm()
      }
    }
  },
  { immediate: true }
)

// 技术标准维护数据结构
const STANDARD_STORAGE_KEY = 'factory_standard_data'
const defaultStandardData = {
  coated: [
    { weight: 100, items: [
      { name: '定量', unit: 'g/m²', standard: '+3/-5' },
      { name: '水份', unit: '%', standard: '8.5±2' }
    ]}
  ],
  corrugated: [
    { weight: 100, items: [
      { name: '定量', unit: 'g/m²', standard: '+3/-5' },
      { name: '水份', unit: '%', standard: '8±2' }
    ]}
  ]
}
const standardData = ref({ ...defaultStandardData })

// 纸种类型列表
const standardPaperTypes = ref([
  { label: '箱板纸', value: 'coated' },
  { label: '高强瓦楞原纸', value: 'corrugated' }
])
const standardEditPaperType = ref('coated')
const standardEditWeights = ref([])

// 读取本地数据
function loadStandardData() {
  const raw = localStorage.getItem(STANDARD_STORAGE_KEY)
  if (raw) {
    try {
      standardData.value = JSON.parse(raw)
    } catch {}
  }
  // 初始化编辑区
  setEditWeightsByType(standardEditPaperType.value)
}
function setEditWeightsByType(type) {
  standardEditWeights.value = standardData.value[type]
    ? JSON.parse(JSON.stringify(standardData.value[type]))
    : []
}

// 切换纸种
watch(standardEditPaperType, (type) => {
  setEditWeightsByType(type)
})

// 新增纸种
function addPaperType() {
  ElMessageBox.prompt('请输入新纸种名称', '新增纸种', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '名称不能为空'
  }).then(({ value }) => {
    const val = value.trim()
    if (!val) return
    // 生成唯一 value
    let key = val
    let idx = 1
    while (standardPaperTypes.value.find(t => t.value === key)) {
      key = val + idx
      idx++
    }
    standardPaperTypes.value.push({ label: val, value: key })
    standardData.value[key] = []
    standardEditPaperType.value = key
  })
}
// 新增克重
function addWeight() {
  standardEditWeights.value.push({ weight: '', items: [] })
}
// 删除克重
function removeWeight(idx) {
  standardEditWeights.value.splice(idx, 1)
}
// 新增指标
function addIndicator(weightIdx) {
  standardEditWeights.value[weightIdx].items.push({ name: '', unit: '', standard: '' })
}
// 删除指标
function removeIndicator(weightIdx, indicatorIdx) {
  standardEditWeights.value[weightIdx].items.splice(indicatorIdx, 1)
}
// 保存
function saveStandardEdit() {
  // 保存当前编辑纸种的数据
  standardData.value[standardEditPaperType.value] = JSON.parse(JSON.stringify(standardEditWeights.value))
  localStorage.setItem(STANDARD_STORAGE_KEY, JSON.stringify(standardData.value))
  ElMessage.success('已保存到本地')
  // standardDialogVisible.value = false // 移除此行
}
// 打开对话框时加载
// function openStandardDialog() { // 移除此函数
//   console.log('openStandardDialog called')
//   loadStandardData()
//   standardDialogVisible.value = true
// }

function onEdit() {
  isEditing.value = !isEditing.value
  ElMessage.success(isEditing.value ? '已进入编辑模式' : '已退出编辑模式')
}

async function generatePDF(fromPreview = false) {
   try {
     // 检查是否正在编辑状态
     if (isEditing.value) {
       ElMessage.warning('请先完成编辑后再导出PDF');
       return;
     }
     
     // 确保签名数据是最新的
     loadSignatureData()
     
     // 验证基本信息表单
     if (baseFormRef.value) {
       try {
         await baseFormRef.value.validate();
       } catch (error) {
         ElMessage.error('请完善基本信息');
         return;
       }
     }
     
     // 验证克重信息
     if (!weightGroups.value.length || weightGroups.value.some(group => !group.weight)) {
       ElMessage.error('请填写所有克重信息');
       return;
     }
     
     // 验证检测数据
     for (const group of weightGroups.value) {
       for (const item of group.items) {
         if (!item.value && item.name !== '横向环压指数') {
           ElMessage.error(`请填写${group.weight}g的${item.name}检测数据`);
           return;
         }
       }
     }
     
     ElMessage.info('正在生成PDF，请稍候...');
     
     // 1. 显示PDF模板div
     pdfVisible.value = true;
    
    // 等待DOM更新完成
    await nextTick();
    
    // 额外等待确保渲染完成
    await new Promise(resolve => setTimeout(resolve, 100));
    
    const pdfDiv = pdfRef.value;
    if (!pdfDiv) {
      throw new Error('PDF模板元素未找到');
    }
    
    // 2. 用html2canvas截取该div
    const canvas = await html2canvas(pdfDiv, { 
      scale: 3.0, 
      useCORS: true,
      allowTaint: true,
      backgroundColor: '#ffffff',
      logging: false,
      removeContainer: true,
      foreignObjectRendering: false,
      imageTimeout: 0,
      ignoreElements: (element) => {
        // 忽略一些可能影响渲染的元素
        return element.classList.contains('el-loading-mask') || 
               element.classList.contains('el-loading-spinner');
      }
    });
    
    const imgData = canvas.toDataURL('image/jpeg', 1.0);
    
    // 3. 生成PDF
    const pdf = new jsPDF('p', 'mm', 'a4');
    pdf.addImage(imgData, 'JPEG', 0, 0, 210, 297);
    
    // 生成文件名：客户名称+首次保存时间
    const customerName = baseInfo.value.customer || '未知客户';
    const firstSavedAt = baseInfo.value.firstSavedAt;
    
    let filename;
    if (firstSavedAt) {
      // 使用首次保存时间生成文件名
      const savedDate = new Date(firstSavedAt);
      const year = savedDate.getFullYear();
      const month = String(savedDate.getMonth() + 1).padStart(2, '0');
      const day = String(savedDate.getDate()).padStart(2, '0');
      const hours = String(savedDate.getHours()).padStart(2, '0');
      const minutes = String(savedDate.getMinutes()).padStart(2, '0');
      const timeStr = `${year}${month}${day}_${hours}${minutes}`;
      filename = `${customerName}_${timeStr}_出厂检验报告.pdf`;
    } else {
      // 如果没有首次保存时间，使用当前时间（兼容旧数据）
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const timeStr = `${year}${month}${day}_${hours}${minutes}`;
      filename = `${customerName}_${timeStr}_出厂检验报告.pdf`;
    }
    
    pdf.save(filename);
    
    ElMessage.success('PDF生成成功！');
    
    // 如果是从预览对话框调用的，关闭预览对话框
    if (fromPreview) {
      previewVisible.value = false;
    }
  } catch (error) {
    ElMessage.error('PDF生成失败：' + error.message);
  } finally {
    // 4. 立即隐藏PDF模板div，避免打印时重复
    pdfVisible.value = false;
    // 额外确保DOM更新
    await nextTick();
  }
}

 async function saveReport() {
   try {
     const reportId = route.params.id;
     // 验证基本信息表单
     if (baseFormRef.value) {
       try {
         await baseFormRef.value.validate();
       } catch (error) {
         ElMessage.error('请完善基本信息');
         return;
       }
     }
     
     // 验证克重信息
     if (!weightGroups.value.length || weightGroups.value.some(group => !group.weight)) {
       ElMessage.error('请填写所有克重信息');
       return;
     }
     
     // 验证检测数据
     for (const group of weightGroups.value) {
       for (const item of group.items) {
         if (!item.value && item.name !== '横向环压指数') {
           ElMessage.error(`请填写${group.weight}g的${item.name}检测数据`);
           return;
         }
       }
     }
     
     let report
     let reportCode
     
     if (reportId && reportId !== 'new' && isSaved.value) {
       // 更新已存在的报告
       const query = new AV.Query('FactoryReport')
       report = await query.get(reportId)
       // 保持原有的报告编号
       const existingBaseInfo = report.get('baseInfo') || {}
       reportCode = existingBaseInfo.reportCode
     } else {
       // 创建新报告
       const FactoryReport = AV.Object.extend('FactoryReport')
       report = new FactoryReport()
       // 预分配报告编号，如果保存失败会回滚
       reportCode = preAllocateReportCode()
     }
     
     // 保存报告编号
     const baseInfoWithCode = {
       ...baseInfo.value,
       reportCode: reportCode
     };
     
     // 如果是首次保存，添加首次保存时间
     if (!reportId || reportId === 'new' || !isSaved.value) {
       baseInfoWithCode.firstSavedAt = new Date().toISOString();
     }
     
     // 基本信息（包含报告编号）
     report.set('baseInfo', JSON.parse(JSON.stringify(baseInfoWithCode)));
     // 克重组
     report.set('weightGroups', JSON.parse(JSON.stringify(weightGroups.value)));
     // 是否使用印章
     report.set('useSeal', useSeal.value);
     // 结论
     report.set('conclusion', conclusion.value);
     // 保存标准快照（只保存新建/首次保存时的快照，编辑时不覆盖）
     if (!reportId || reportId === 'new' || !isSaved.value) {
       report.set('standardSnapshot', JSON.parse(JSON.stringify({
         weightGroups: weightGroups.value,
         selectedTemplate: selectedTemplate.value,
         corrugatedLevel: corrugatedLevel.value,
         level: baseInfo.value.level,
         standardVersionId: getCurrentStandardVersionId ? getCurrentStandardVersionId() : undefined // 如有标准版本号
       })));
     }
     // ACL
     const acl = new AV.ACL();
     acl.setPublicReadAccess(true);
     acl.setPublicWriteAccess(true);
     report.setACL(acl);
     await report.save();
     isSaved.value = true
     isEditing.value = false
     ElMessage.success('报告已保存！');
   } catch (e) {
     // 如果是新建报告且保存失败，回滚报告编号
     if (!reportId || reportId === 'new' || !isSaved.value) {
       rollbackReportCode();
     }
     ElMessage.error('保存失败：' + (e.message || e.rawMessage));
   }
 }

// 加载报告数据
async function loadReport(id) {
  try {
    const query = new AV.Query('FactoryReport')
    const report = await query.get(id)
    
    // 加载基本信息
    const savedBaseInfo = report.get('baseInfo') || {}
    baseInfo.value = {
      date: savedBaseInfo.date || new Date().toISOString().split('T')[0],
      customer: savedBaseInfo.customer || '',
      plate: savedBaseInfo.plate || '',
      product: savedBaseInfo.product || '滦星牌箱板纸',
      level: savedBaseInfo.level || '一级',
      reportCode: savedBaseInfo.reportCode || '',
      firstSavedAt: savedBaseInfo.firstSavedAt || '',
      inspectorName: savedBaseInfo.inspectorName || '' // 加载保存的检验员信息
    }
    
    // 根据产品名称设置模板类型
    if (savedBaseInfo.product === '滦月牌高强瓦楞原纸') {
      selectedTemplate.value = 'corrugated'
      // 根据保存的等级设置corrugatedLevel
      if (savedBaseInfo.level === 'AAA级') {
        corrugatedLevel.value = 'AAA级'
      } else {
        corrugatedLevel.value = 'A级'
      }
    } else {
      selectedTemplate.value = 'coated'
    }
    
    // 优先加载标准快照
    const dbStandardSnapshot = report.get('standardSnapshot')
    if (dbStandardSnapshot && dbStandardSnapshot.weightGroups) {
      weightGroups.value = dbStandardSnapshot.weightGroups
      selectedTemplate.value = dbStandardSnapshot.selectedTemplate || 'coated'
      if (dbStandardSnapshot.selectedTemplate === 'corrugated') {
        corrugatedLevel.value = dbStandardSnapshot.corrugatedLevel || 'A级'
      } else {
        baseInfo.value.level = dbStandardSnapshot.level || '一级'
      }
      groupId = Math.max(...dbStandardSnapshot.weightGroups.map(g => g.id)) + 1
      // 保存快照到响应式变量
      standardSnapshot.value = dbStandardSnapshot
    } else {
      // 兼容老数据
      const savedWeightGroups = report.get('weightGroups') || []
      if (savedWeightGroups.length > 0) {
        weightGroups.value = savedWeightGroups
        groupId = Math.max(...savedWeightGroups.map(g => g.id)) + 1
      }
      // 清空快照
      standardSnapshot.value = null
    }
    
    // 加载其他设置
    useSeal.value = report.get('useSeal') || false
    
    // 设置为已保存状态
    isSaved.value = true
    isEditing.value = false
    
    ElMessage.success('报告加载成功！')
  } catch (error) {
    ElMessage.error('加载报告失败：' + error.message)
  }
}

// 显示标准版本号
const displayStandardVersionId = computed(() => {
  // 优先用快照
  if (standardSnapshot.value && standardSnapshot.value.standardVersionId) {
    return standardSnapshot.value.standardVersionId;
  }
  // 新建/编辑时可用当前标准版本号
  if (typeof getCurrentStandardVersionId === 'function') {
    const versionId = getCurrentStandardVersionId();
    return versionId || '--';
  }
  return '--';
});

// 监听模板变化，更新标准版本号显示
// 签名相关函数
function openSignatureManage() {
  signatureDialogVisible.value = true
  // 加载当前签名数据
  loadSignatureData()
}

function loadSignatureData() {
  try {
    const signatures = JSON.parse(localStorage.getItem('pdf_signatures') || '{}')
    const settings = JSON.parse(localStorage.getItem('pdf_signature_settings') || '{}')
    
    // 只保留SVG格式的签名，删除图片格式
    const inspectorSignature = signatures.inspector && signatures.inspector.includes('<svg') ? signatures.inspector : ''
    const reviewerSignature = signatures.reviewer && signatures.reviewer.includes('<svg') ? signatures.reviewer : ''
    
    // 获取检验员姓名的逻辑（与SignatureManage.vue保持一致）
    const currentUsername = localStorage.getItem('currentUsername') || '未知用户'
    const userRoleFromStorage = localStorage.getItem('userRole') || 
                               localStorage.getItem('currentUserRole') || 
                               localStorage.getItem('role') || 
                               'user'
    const currentUserRole = userRoleFromStorage
    
    // 预设检验人员列表（普通用户的用户名）
    const presetInspectors = ['葛岑茹', '葛爽', '李秋月', '张小娟', '杨雅静', '朱萍萍', '蔡艳花', '甄利蕊', '赵金蓉']
    
    // 检查报告中是否已经保存了检验员信息
    let inspectorName = baseInfo.value.inspectorName
    
    // 如果没有保存的检验员信息，则动态生成
    if (!inspectorName) {
      if (currentUserRole === 'admin' || currentUserRole === 'superadmin') {
        // 管理员登录时，随机选择一个预设检验人员
        const randomIndex = Math.floor(Math.random() * presetInspectors.length)
        inspectorName = presetInspectors[randomIndex]
        // 将随机分配的检验员保存到报告中
        baseInfo.value.inspectorName = inspectorName
      } else {
        // 普通用户登录时，使用当前用户名
        inspectorName = currentUsername
        // 将用户名保存到报告中
        baseInfo.value.inspectorName = inspectorName
      }
      
      // 如果是已保存的报告，立即更新数据库中的检验员信息
      if (isSaved.value && route.params.id && route.params.id !== 'new') {
        updateInspectorInDatabase(inspectorName)
      }
    }
    
    // 生成检验人员文本签名
    function generateInspectorTextSignature(name) {
      return `<svg width="200" height="60" xmlns="http://www.w3.org/2000/svg">
      <text x="10" y="27" font-family="Arial, Microsoft YaHei, sans-serif" font-size="16" fill="#000" font-weight="normal">${name}</text>
      <line x1="10" y1="35" x2="${Math.max(80, name.length * 10)}" y2="35" stroke="#000" stroke-width="1"/>
    </svg>`
    }
    
    const generatedInspectorSignature = generateInspectorTextSignature(inspectorName)
    
    signatureData.value = {
      inspector: {
        name: inspectorName,
        signature: generatedInspectorSignature,
        style: settings.signatureStyle || 'handwritten'
      },
      reviewer: {
        name: settings.reviewerName || '姚俊磊',
        signature: reviewerSignature,
        style: settings.signatureStyle || 'handwritten'
      }
    }
  } catch (error) {
    console.error('加载签名数据失败:', error)
  }
}

// 更新数据库中的检验员信息
async function updateInspectorInDatabase(inspectorName) {
  try {
    const reportId = route.params.id
    if (reportId && reportId !== 'new') {
      const query = new AV.Query('FactoryReport')
      const report = await query.get(reportId)
      
      // 更新baseInfo中的检验员信息
      const currentBaseInfo = report.get('baseInfo') || {}
      currentBaseInfo.inspectorName = inspectorName
      report.set('baseInfo', JSON.parse(JSON.stringify(currentBaseInfo)))
      
      await report.save()
      console.log('检验员信息已更新到数据库:', inspectorName)
    }
  } catch (error) {
    console.error('更新检验员信息失败:', error)
  }
}

function saveSignatureSettings() {
  if (signatureManageRef.value) {
    const data = signatureManageRef.value.getSignatureData()
    signatureData.value = data
    ElMessage.success('签名设置已保存')
    signatureDialogVisible.value = false
  }
}



watch(selectedTemplate, () => {
  // 强制更新标准版本号显示
  nextTick(() => {
    // 触发计算属性重新计算
  })
})
</script>

<style scoped>
.factory-report-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.factory-report-card {
  max-width: 1200px;
  min-width: 800px;
  margin: 0 auto;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  background: #fff;
}

/* 页面头部样式 */
.report-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 40px;
  padding-bottom: 24px;
  border-bottom: 2px solid #f0f0f0;
}

.header-left .page-title {
  font-size: 32px;
  font-weight: 700;
  color: #1677ff;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #1677ff, #409eff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-left .page-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
  font-weight: 400;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 统一按钮基础样式 */
.header-right .back-btn,
.header-right .standard-btn,
.header-right .new-report-btn {
  font-weight: 600;
  font-size: 14px;
  padding: 10px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  height: 40px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 返回列表按钮样式 */
.header-right .back-btn {
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  color: #666;
}

.header-right .back-btn:hover {
  background: #e6f7ff;
  border-color: #91d5ff;
  color: #1677ff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.15);
}

/* 查看技术标准按钮样式 */
.header-right .standard-btn {
  background: linear-gradient(135deg, #ff9800, #f39c12);
  border: none;
  color: #fff;
}

.header-right .standard-btn:hover {
  background: linear-gradient(135deg, #f57c00, #e68900);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 152, 0, 0.3);
}

/* 新建报告按钮样式 */
.header-right .new-report-btn {
  background: linear-gradient(135deg, #1677ff, #409eff);
  border: none;
  color: #fff;
}

.header-right .new-report-btn:hover {
  background: linear-gradient(135deg, #0958d9, #1677ff);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.3);
}

/* 按钮内容对齐 */
.header-right .back-btn :deep(.el-button__content),
.header-right .standard-btn :deep(.el-button__content),
.header-right .new-report-btn :deep(.el-button__content) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100%;
  text-align: center;
}

.add-weight-btn {
  font-weight: 600;
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(22, 119, 255, 0.2);
  transition: all 0.3s ease;
}

.add-weight-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.3);
}

/* 带删除按钮的自动完成组件样式 */
.autocomplete-with-delete {
  display: flex;
  align-items: center;
  gap: 8px;
}

.autocomplete-with-delete .el-autocomplete {
  flex: 1;
}

.delete-history-btn {
  flex-shrink: 0;
  padding: 8px;
  height: 32px;
  width: 32px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.delete-history-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
}

.delete-history-btn .el-icon {
  font-size: 14px;
}

/* 基本信息表单样式 */
.base-form {
  background: #fafbfc;
  padding: 24px;
  border-radius: 12px;
  border: 1px solid #e8e8e8;
}

.report-code-row,
.standard-version-row {
  font-size: 14px !important;
  margin-bottom: 8px !important;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -12px 20px -12px;
}

.form-item {
  margin-bottom: 0;
}

.form-input {
  width: 100%;
}

.form-col {
  flex: 0 0 50%;
  padding: 0 12px;
  box-sizing: border-box;
}

/* 克重组样式 */
.weight-groups-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.weight-group-card {
  transition: all 0.3s ease;
}

.group-card {
  border-radius: 12px;
  border: 1px solid #e8e8e8;
  transition: all 0.3s ease;
}

.group-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8fbff;
  border-bottom: 1px solid #e8e8e8;
  border-radius: 12px 12px 0 0;
}

.group-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.weight-input-item {
  margin-bottom: 0;
}

.weight-input {
  width: 120px;
}

.weight-suffix {
  margin-left: 8px;
  color: #999;
  font-size: 14px;
}

.delete-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  transform: scale(1.05);
}

.data-table {
  margin: 0;
  border-radius: 0 0 12px 12px;
}

.table-wrapper {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 16px;
}

/* 添加克重组按钮区域样式 */
.add-weight-section {
  margin-top: 24px;
  padding: 20px;
  background: #f8fbff;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
  text-align: center;
}

.add-weight-btn {
  font-weight: 600;
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 auto;
}

.add-weight-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.2);
}

.add-weight-btn:disabled {
  transform: none;
  box-shadow: none;
}

/* 结论和设置样式 */
.conclusion-section {
  background: #fafbfc;
  padding: 24px;
  border-radius: 12px;
  border: 1px solid #e8e8e8;
}

.seal-setting {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.seal-switch {
  margin-right: 8px;
}

.seal-desc {
  color: #666;
  font-size: 14px;
}

.conclusion-display {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.conclusion-label {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.conclusion-tag {
  font-size: 16px;
  padding: 8px 16px;
  border-radius: 6px;
}

/* 状态和操作按钮样式 */
.action-section {
  margin-top: 40px;
  padding-top: 24px;
  border-top: 2px solid #f0f0f0;
}



.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.primary-actions,
.secondary-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  font-weight: 600;
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-btn:disabled {
  transform: none;
  box-shadow: none;
}
.pdf-report-template {
  font-family: 'NotoSansSC', 'SimSun', 'Arial', sans-serif;
}

/* 预览对话框样式 */
.preview-dialog {
  .el-dialog__body {
    padding: 0;
    max-height: 80vh;
    overflow: auto;
  }
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
  background: #f5f5f5;
  min-height: 600px;
}

.preview-template {
  width: 210mm;
  height: 297mm;
  padding: 1.5cm;
  box-sizing: border-box;
  background: #fff;
  border: 1px solid #ccc;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: scale(0.8);
  transform-origin: top center;
}

.dialog-footer {
  text-align: right;
  padding: 20px;
  border-top: 1px solid #e4e7ed;
}
.pdf-report-template table, .pdf-report-template th, .pdf-report-template td {
  border: 1px solid #222;
}
   .pdf-th, .pdf-td {
    text-align: center;
    vertical-align: middle;
    height: 45px;
    padding: 0 8px;
    font-size: 14px;
  }
 
 .required-input {
   border-color: #409eff;
 }
 
 .required-input:focus {
   border-color: #409eff;
   box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
 }



@media print {
  body {
    background: #fff !important;
  }
  /* 只打印报告卡片 */
  .factory-report-container,
  .factory-report-card {
    box-shadow: none !important;
    border: none !important;
    background: #fff !important;
    margin: 0 !important;
    padding: 0 !important;
    width: 100% !important;
  }
  /* 隐藏操作按钮、添加克重组、输入框、提示等 */
  .el-button,
  .add-weight-section,
  .action-section,
  .input-tip,
  .el-form-item__error,
  .el-input,
  .el-select,
  .el-autocomplete,
  .weight-suffix {
    display: none !important;
  }
  /* 隐藏单项判定结果列（如有） */
  .el-table__body-wrapper td:last-child,
  .el-table__header-wrapper th:last-child {
    display: none !important;
  }
  /* 只保留主表格线 */
  table, th, td {
    border: 1px solid #000 !important;
  }
}

/* 表单区域样式 */
.form-section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
  position: relative;
  padding-left: 16px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #1677ff, #409eff);
  border-radius: 2px;
}

.section-divider {
  flex: 1;
  height: 1px;
  background: linear-gradient(90deg, #e8e8e8, transparent);
  margin: 0 16px;
}

.add-weight-btn {
  font-weight: 600;
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(22, 119, 255, 0.2);
  transition: all 0.3s ease;
}

.add-weight-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.3);
}

/* 移动端适配 */
@media (max-width: 700px) {
  .factory-report-container {
    padding: 8px;
  }
  
  .factory-report-card {
    padding: 16px;
    border-radius: 12px;
    min-width: unset;
  }
  
  .report-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
    margin-bottom: 24px;
    padding-bottom: 16px;
  }
  
  .header-left .page-title {
    font-size: 20px;
  }
  
  .header-left .page-subtitle {
    font-size: 14px;
  }
  
  .header-right {
    width: 100%;
    justify-content: flex-start;
    gap: 8px;
    flex-wrap: wrap;
  }
  
  .header-right .back-btn,
  .header-right .standard-btn,
  .header-right .new-report-btn {
    min-width: 100px;
    padding: 8px 16px;
    font-size: 14px;
    height: 36px;
  }
  
  .form-section {
    margin-bottom: 24px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .section-title {
    font-size: 18px;
  }
  
  .el-form-item {
    margin-bottom: 16px;
  }
  
  .el-form-item__label {
    font-size: 15px !important;
  }
  
  .el-input, .el-select, .el-autocomplete, .el-date-picker {
    font-size: 16px !important;
    min-height: 38px !important;
  }
  
  .el-table {
    font-size: 13px;
    min-width: 600px;
    overflow-x: auto;
    display: block;
  }
  
  .el-table__body-wrapper {
    overflow-x: auto !important;
  }
  
  .el-button {
    font-size: 16px !important;
    min-height: 38px !important;
  }
  
  .el-dialog {
    width: 98vw !important;
    min-width: unset !important;
    max-width: 100vw !important;
    margin: 0 auto;
  }
  
  .el-form-item__content {
    margin-left: 0 !important;
  }
  
  .el-form--label-top .el-form-item__label {
    padding: 0 0 8px 0;
  }
  
  .form-row {
    display: block !important;
    margin: 0 0 0 0 !important;
  }
  
  .form-col {
    margin-bottom: 16px;
    width: 100% !important;
    flex: none !important;
    padding: 0 !important;
  }
  
  .weight-group-card {
    margin-bottom: 16px;
  }
  
  .group-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .group-title {
    width: 100%;
  }
  
  .weight-input-item {
    margin-bottom: 8px;
  }
  
  .weight-input {
    width: 100%;
  }
  
  .data-table {
    margin-top: 12px;
  }
  
  .table-wrapper {
    margin-top: 12px;
  }
  
  .action-section {
    margin-top: 24px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 12px;
  }
  
  .primary-actions,
  .secondary-actions {
    display: flex;
    gap: 8px;
    justify-content: center;
  }
  
  .action-btn {
    flex: 1;
    min-width: 120px;
  }
  
  /* 移动端删除按钮样式 */
  .autocomplete-with-delete {
    flex-direction: column;
    gap: 8px;
  }
  
  .delete-history-btn {
    align-self: flex-end;
    padding: 6px;
    height: 28px;
    width: 28px;
  }
}
</style> 